import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAppStore } from '@/stores/useAppStore';
import { userApi } from '@/api/user';

export const useAuth = () => {
  const navigate = useNavigate();
  const { user, isAuthenticated, setUser, setAuthenticated, setLoading } = useAppStore();
  const [isChecking, setIsChecking] = useState(true);

  // 检查用户认证状态
  const checkAuth = async () => {
    const token = localStorage.getItem('token');
    
    if (!token) {
      setIsChecking(false);
      return;
    }

    try {
      setLoading(true);
      const response = await userApi.getUserInfo();
      const userData = response.data.data;
      
      setUser(userData);
      setAuthenticated(true);
    } catch (error) {
      console.error('❌ 认证检查失败:', error);
      // 清除无效token
      localStorage.removeItem('token');
      setUser(null);
      setAuthenticated(false);
    } finally {
      setLoading(false);
      setIsChecking(false);
    }
  };

  // 登录
  const login = async (email: string, password: string) => {
    try {
      setLoading(true);
      const response = await userApi.login({ email, password });
      const { user: userData, token } = response.data.data;
      
      // 保存token
      localStorage.setItem('token', token);
      
      // 更新状态
      setUser(userData);
      setAuthenticated(true);
      
      return { success: true, user: userData };
    } catch (error: any) {
      console.error('❌ 登录失败:', error);
      return { 
        success: false, 
        error: error.message || '登录失败，请检查邮箱和密码' 
      };
    } finally {
      setLoading(false);
    }
  };

  // 登出
  const logout = async () => {
    try {
      await userApi.logout();
    } catch (error) {
      console.error('❌ 登出API调用失败:', error);
    } finally {
      // 清除本地状态
      localStorage.removeItem('token');
      setUser(null);
      setAuthenticated(false);
      navigate('/login');
    }
  };

  // 注册
  const register = async (name: string, email: string, password: string) => {
    try {
      setLoading(true);
      const response = await userApi.register({ 
        name, 
        email, 
        password, 
        confirmPassword: password 
      });
      const { user: userData, token } = response.data.data;
      
      // 保存token
      localStorage.setItem('token', token);
      
      // 更新状态
      setUser(userData);
      setAuthenticated(true);
      
      return { success: true, user: userData };
    } catch (error: any) {
      console.error('❌ 注册失败:', error);
      return { 
        success: false, 
        error: error.message || '注册失败，请检查输入信息' 
      };
    } finally {
      setLoading(false);
    }
  };

  // 初始化时检查认证状态
  useEffect(() => {
    checkAuth();
  }, []);

  return {
    user,
    isAuthenticated,
    isChecking,
    login,
    logout,
    register,
    checkAuth,
  };
};
